package com.gmall.batch.gmallbatch.config;

import com.gmall.batch.gmallbatch.handle.process.FileDataProcess;
import com.gmall.batch.gmallbatch.handle.read.FileDataReader;
import com.gmall.batch.gmallbatch.handle.writer.FileDataWriter;
import com.gmall.batch.gmallbatch.listener.FileParseCompletionListener;
import io.netty.channel.ConnectTimeoutException;
import org.apache.commons.compress.archivers.dump.DumpArchiveException;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.DeadlockLoserDataAccessException;

/**
 * @author HL.Wu
 * @date 2020/7/6 17:18
 * gmall-service
 *
 * for: 文件解析配置操作流程步骤
 */
@Configuration
@EnableBatchProcessing
public class FileParseDataConfig {

    @Autowired
    private JobBuilderFactory jobBuilderFactory; // 初始化任务构建工厂
    @Autowired
    private StepBuilderFactory stepBuilderFactory; // 初始化执行步骤构建工厂
    @Autowired
    private FileParseCompletionListener fileParseCompletionListener;
    @Autowired
    private FileDataReader fileDataReader;
    @Autowired
    private FileDataProcess fileDataProcess;
    @Autowired
    private FileDataWriter fileDataWriter;

    @Bean
    public Job fileParseJob(){
        return jobBuilderFactory.get("fileParseJob").incrementer(new RunIdIncrementer()).listener(fileParseCompletionListener).flow(fileParseStep()).end().build();
    }

    @Bean
    public Step fileParseStep(){
        return stepBuilderFactory.get("fileParseStep")
                .<String,String>chunk(3)
                .reader(fileDataReader)
                .processor(fileDataProcess)
                .writer(fileDataWriter)
                .faultTolerant()
                .retry(ConnectTimeoutException.class)
                .retry(DeadlockLoserDataAccessException.class)
                .skip(UnexpectedInputException.class) // 错误跳过执行
                .skip(ParseException.class)
                .skip(Exception.class) // 错误跳过执行
                .build();
    }
}
